import axios from 'axios'
import { getToken } from './token'
import history from 'utils/history'
import { message } from 'antd'

export const baseURL = 'http://geek.itheima.net/v1_0'
const instance = axios.create({
  baseURL,
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    config.headers.Authorization = `Bearer ${token}`
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (error?.response?.status === 401) {
      history.push('/login')
      message.warning('尊敬的用户，你过期了')
    } else {
      message.error('尊敬的用户，服务器繁忙')
    }
    return Promise.reject(error)
  }
)

export default instance
